package com.cimu.redis.pubsub;

import com.cimu.redis.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class RedisReceiver {
    @Autowired
    private RedisTemplate<Serializable, Serializable> rt;

    /**
     * 接收消息
     * @param msg 消息字符串
     * @param channel 通道
     */
    public void receiveMessage(String msg, String channel) {
        try {
            Message m = (Message)rt.getValueSerializer().deserialize(msg.getBytes("UTF-8"));
            List<MessageHandler> handlers = SpringContextUtils.getBeans(MessageHandler.class);
            for (MessageHandler handler : handlers) {
                if (Arrays.asList(handler.messageType()).contains(m.getType())) {
                    handler.processMsg(m);
                }
            }
        } catch (Exception e) {
            log.error("redis接收异常:",e);
        }
    }
}